<?php
include_once 'application/application.php';


class Page_views {

    private $tableviews = 'views_object_list';
    private $tablevgroup = 'views_group_list';
    private $tablecnc = 'views_conception_list';
    private $tablefloors = 'views_floors_list';
    private $tablesen = 'views_floors_sensors_list';



    public $action;
    public $error;



    public function __construct() {
        $this->action = Arr::getValue($_POST, 'action', false);

        DB::connect();
        if (!DB::state()) {
            $this->error = DB::getError();
        }
    }


    public function __destruct() {

    }



    function fillData () {
        if (!ConceptionsCollection::Init())
            $this->error = 'Проблемы со списком концепций';
        $params = array();

        $id = Arr::getValue($_POST, 'id', 0);

        $alles = array(
            'views' => getAllViews(),
            'cities' => getAllCities(),
            'vgroups' => getAllViewsGroups(),
            'conceptions' => ConceptionsCollection::allRowsById(),
            'types' => getObjTypes(),
            'btypes' => getBuildTypes(),
            'datatypes' => getDataTypes()
        );
        
        $q = "  SELECT fl.view_id, ds.tbl 
                FROM 
                    {$this->tablefloors} fl, 
                    {$this->tablesen} ds
                WHERE fl.id = ds.floor_id";
        $res = DB::query($q);
        $tables = array();            
        if (DB::$lastReqState)  {
            while ($row = $res->fetch_assoc()) {
                $vid = Arr::getValue($row, 'view_id', FALSE);
                $tbl = Arr::getValue($row, 'tbl', FALSE);
                if ($vid) {
                    if (!Arr::getValue($tables, $vid)) $tables[$vid] = array();
                    if (!in_array($tbl, $tables[$vid])) $tables[$vid][] = $tbl;
                }
            }
        }     
        $alles['tables'] = $tables;

        if ($id) {
            $params = Arr::getValue($alles['views'], $id, false);
            if (!$params) {
                $this->error = 'Отображение не существует';
                return $alles;
            }

            $params['view_mode'] = 1; // !!!!!!

        }

        foreach ($alles as $key => $val) {
            $params[$key] = $val;
        }

        return $params;
    }

    function addVisualParams($item) {
        $views = getAllViews();
        $cities = getAllCities();
        //$vgroups = getAllViewsGroups();
        $conceptions = ConceptionsCollection::allRowsById();
        $types = getObjTypes();

        if(array_key_exists('parent_id', $item)) $item['parent_name'] = $item['parent_id']? Arr::getValue(Arr::getValue($views, $item['parent_id'],array()), 'obj_name', '?') : 'Отдельное здание';
        if(array_key_exists('obj_type', $item)) $item['obj_type_text'] = array_key_exists($item['obj_type']+1, $types)? $types[$item['obj_type']+1]['name'].', '.$types[$item['obj_type']+1]['datatypename'] : $item['obj_type'];
        $item['city_name'] = $item['city_id']? Arr::getValue(Arr::getValue($cities, $item['city_id'], array()), 'city_name', '?') : 'Нет';
        $item['cnc_name'] = $item['conception']? Arr::getValue(Arr::getValue($conceptions, $item['conception'], array()), 'name', '?') : 'Нет';
        return $item;
    }



    function fieldRead(&$J) {
        $params = array();

        $params['id'] = Arr::getValue($_POST, 'vw_id', 0);

        $params['action']           = $J->readVar('action');
        $params['vw_id']            = (int)$J->readVar('vw_id',0);
        $params['view_mode']        = (int)($J->readVar('view_mode', 1));
        $params['obj_name']         = mysql_escape_string($J->readVar('obj_name'));
        $params['obj_type']         = (int)($J->readVar('obj_type'));
        $params['build_type']       = (int)($J->readVar('build_type',0));
        $params['parent_id']        = (int)($J->readVar('parent_id'));
        $params['group']            = (int)($J->readVar('group'));
        $params['obj_short_name']   = mysql_escape_string($J->readVar('obj_short_name'));
        $params['city_id']          = (int)($J->readVar('city_id'));
        $params['address']          = mysql_escape_string($J->readVar('address'));
        $params['lattitude']        = mysql_escape_string($J->readVar('lattitude',0));
        $params['longitude']        = mysql_escape_string($J->readVar('longitude',0));
        $params['area']             = (int)($J->readVar('area',0));
        $params['conception']       = (int)($J->readVar('conception'));
        $params['dev']              = (int)($J->readVar('dev',0));
        $params['viewable']         = (int)($J->readVar('viewable',1));
        $params['is_new']           = (int)($J->readVar('is_new',0));
        $params['def_floor']        = (int)($J->readVar('def_floor',0));

        return $params;
    }


    public function checkFields($params) {
        $wrongFields = array();


        $name = 'view_mode';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'obj_name';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'obj_type';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'build_type';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'obj_short_name';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var && $params['group']) $msg = 'Не заполнено поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'city_id';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'address';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;
/*
        $name = 'lattitude';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'longitude';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;
*/
        $name = 'conception';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;


        return $wrongFields;

    }



    public function itemAdd($params = null) {

        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        if (!is_array($params)) {
            $params = $this->fieldRead($J);
            $wrongFields = $this->checkFields($params);

            if (count($wrongFields)) {
                $J->wrongFields = $wrongFields;
                return $J;
            }
        }

        $params = array_merge(array(
            'obj_name'          => '?',
            'obj_type'          => 0,
            'build_type'        => 0,
            'parent_id'         => 0,
            'group'             => 0,
            'obj_short_name'    => '',
            'city_id'           => 0,
            'address'           => '',
            'lattitude'         => 0,
            'longitude'         => 0,
            'area'              => 0,
            'conception'        => 0,
            'dev'               => 1,
            'viewable'          => 0,
            'is_new'            => 1
        ), $params);


        $q = "INSERT INTO `{$this->tableviews}`
                (
                    `id`,
                    `obj_name`,
                    `obj_type`,
                    `build_type`,
                    `parent_id`,
                    `group`,
                    `obj_short_name`,
                    `city_id`,
                    `address`,
                    `lattitude`,
                    `longitude`,
                    `area`,
                    `conception`,
                    `dev`,
                    `viewable`,
                    `is_new`
                )
                VALUES
                (
                    NULL,
                    '{$params['obj_name']}',
                    '{$params['obj_type']}',
                    '{$params['build_type']}',
                    '{$params['parent_id']}',
                    '{$params['group']}',
                    '{$params['obj_short_name']}',
                    '{$params['city_id']}',
                    '{$params['address']}',
                    '{$params['lattitude']}',
                    '{$params['longitude']}',
                    '{$params['area']}',
                    '{$params['conception']}',
                    '{$params['dev']}',
                    '{$params['viewable']}',
                    '{$params['is_new']}'
                )";



        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
            return $J;
        }

        $J->insertedId = DB::$mysqli->insert_id;

        $params['id'] = $J->insertedId;
        if (class_exists('Log')) Log::Save(OPERATION::CREATE_VIEW, $params);

        return $J;

    }



    public function itemAddFromHistoryObject() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $id        = (int)$J->readVar('ho_id',0);
        //$params['vw_id']   = (int)$J->readVar('vw_id',0);


        $q = "  SELECT * FROM `admin_conn_history`
                WHERE id = {$id}
                LIMIT 0,1";

        $res = DB::query($q);

        if (!$res || !DB::state()) return $J->error('Ошибка при работе с базой данных <!--'.DB::getError().'-->');

        $row = mysqli_fetch_array($res, MYSQLI_ASSOC);
        if (!$row) return $J->error('Запись не найдена');

        $params = array(
            'obj_name'          => $row['name'],
            'obj_type'          => $row['obj_type'],
            'build_type'        => $row['build_type'],
            'parent_id'         => 0,
            'group'             => 0,
            'obj_short_name'    => '',
            'city_id'           => 0,
            'address'           => $row['address'],
            'lattitude'         => 0,
            'longitude'         => 0,
            'area'              => 0,
            'conception'        => 0,
            'dev'               => 1,
            'viewable'          => 0,
            'is_new'            => 1
        );


        $J1 = $this->itemAdd($params);
        if (!$J1->getState()) return $J->error($J1->getErrorString ());

        $J->vwId = $J1->insertedId;;
        $J->vwName = $row['name'];


        $q = "UPDATE `admin_conn_history`
              SET view_id = $J->vwId
              WHERE id = {$id}";
        $res = DB::query($q);
        if (!$res || !DB::state()) return $J->error('Ошибка при работе с базой данных <!--'.DB::getError().'-->');



        $J2 = $this->floorCreate($J->vwId);
        if (!$J2->getState()) return $J;//->error ($J2->getErrorString ());
        else $J->flId = $J2->insertedId;


        $J3 = $this->createFLDS(array(
            'floor_id'      => $J->flId,
            'tbl'           => $row['tbl'],
            'sen'           => $row['sen'],
            'time_min'      => 0,
            'time_max'      => 0,
            'time_shift'    => 0,
            'whatsum'       => '',
            'use_timelimit' => 0
        )) ;
        if (!$J3->getState()) return $J;//->error ($J3->getErrorString ());
        else $J->fldsId = $J3->insertedId;

        return $J;
    }














    public function itemUpdate() {

        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = $this->fieldRead($J);
        $wrongFields = $this->checkFields($params);



        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }

        $all = getAllViews_(); // array('byId'=>array(), 'byFio'=>array());
        if (!DB::$lastReqState) return $J->error('Не удалось получить список отображений <!--'.DB::getError().'-->');

        $old_val = Arr::getValue($all, $params['vw_id'], false);
        if (!is_array($old_val)) return $J->error('Отображение не существует');




        $q = "UPDATE `{$this->tableviews}`
              SET
                    `obj_name` = '{$params['obj_name']}',
                    `obj_type` = '{$params['obj_type']}',
                    `build_type` = '{$params['build_type']}',
                    `parent_id` = '{$params['parent_id']}',
                    `group` = '{$params['group']}',
                    `obj_short_name` = '{$params['obj_short_name']}',
                    `city_id` = '{$params['city_id']}',
                    `address` = '{$params['address']}',
                    `lattitude` = '{$params['lattitude']}',
                    `longitude` = '{$params['longitude']}',
                    `area` = '{$params['area']}',
                    `conception` = '{$params['conception']}',
                    `dev` = '{$params['dev']}',
                    `viewable` = '{$params['viewable']}',
                    `is_new` = '{$params['is_new']}'
              WHERE id = {$params['vw_id']}";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
        }

        $J->insertedId = $params['vw_id'];//DB::$mysqli->insert_id;
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VIEW, array('old_value'=>$old_val, 'new_value'=>$params, 'id'=>$params['vw_id']));

        $params = $this->addVisualParams($params);

        //$J->parent_name = Arr::getValue($params, 'parent_name', '');
        //$J->obj_type_text = Arr::getValue($params, 'obj_type_text', '');
        $J->city_name = Arr::getValue($params, 'city_name', '');
        $J->cnc_name = Arr::getValue($params, 'cnc_name', '');

        return $J;


    }


    public function getFloors() {
        $J = new JSON();
        $params['vw_id'] = (int)$J->readVar('vw_id',0);
        $J->readVar('action');
        if (!Auth::isLogged()) return $J->error('not_logged');

        $floors = getFloorsByViewId($params['vw_id']);
        $J->floors = $floors['byOrder'];
        if (!DB::$lastReqState) return $J->error('Не удалось получить список срезов данных <!--'.DB::getError().'-->');
        if (!$params['vw_id']) return $J;

        $q = "SELECT * FROM `{$this->tableviews}` WHERE id = {$params['vw_id']}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка чтения данных <!--('.DB::$mysqli->error.')-->');
        }
        $row = $res->fetch_assoc();
        if (is_array($row)) $J->view = $row;

        return $J;
    }


    public function floorCreate($vw_id=null) {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['view_id'] = (int)$J->readVar('vw_id',0);
        $params['view_id'] = (is_null($vw_id))?  (int)$J->readVar('vw_id',0) : $vw_id;
        $J->readVar('action');

        $all = getAllViews_();
        if (!DB::$lastReqState) return $J->error('Не удалось получить список отображений <!--'.DB::getError().'-->');
        if (!is_array(Arr::getValue($all, $params['view_id'], false))) return $J->error('Отображение не найдено');

        $floors = getFloorsByViewId($params['view_id']);
        $maxOrder = 0;
        if (is_array($floors['byOrder'])) {
            $c = count($floors['byOrder']);
            if ($c) {
                $m = Arr::getValue($floors['byOrder'],$c-1,false);
                if ($m) $maxOrder = $m->view_order;
            }
        }

        $params['name'] = 'new';
        $params['view_order'] = $maxOrder+1;
        $params['picture'] = '';

        $q = "
            INSERT INTO `{$this->tablefloors}`
                        (id,   name,                view_id,              view_order)
            VALUES      (NULL, '{$params['name']}', {$params['view_id']}, {$params['view_order']} )
        ";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка записи данных <!--('.DB::$mysqli->error.')-->');
        }
        $J->insertedId = DB::$mysqli->insert_id;
        $params['id'] = $J->insertedId;
        $J->floor = $params;

        if (class_exists('Log')) Log::Save(OPERATION::CREATE_VWFLOOR, $params);
        return $J;
    }



    public function floorUpdateName() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['id']       = (int)$J->readVar('id',0);
        $params['vw_id'] = (int)$J->readVar('vw_id',0);
        $params['name']     = mysql_escape_string($J->readVar('name'));

        $floors = getFloorsByViewId($params['vw_id']);
        $fl = Arr::getValue($floors['byId'], $params['id'], false);
        if (!$fl) return $J->error('Срез данных не найден');

        $q = "UPDATE `{$this->tablefloors}`
              SET name = '{$params['name']}'
              WHERE id = {$params['id']}";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
        }

        $J->insertedId = DB::$mysqli->insert_id;
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VWFLOOR_NAME, array('old_value'=>$fl->name, 'new_value'=>$params['name'], 'id'=>$params['id']));

        $fl->name = $params['name'];
        $J->floor = $fl;

        return $J;
    }



    public function setDefaultFloor() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['id']       = (int)$J->readVar('id',0);
        $params['vw_id'] = (int)$J->readVar('vw_id',0);


        $all = getAllViews_();
        if (!DB::$lastReqState) return $J->error('Не удалось получить список отображений <!--'.DB::getError().'-->');
        $oldval = Arr::getValue($all, $params['vw_id'], false);
        if (!is_array($oldval)) return $J->error('Отображение не найдено');

        $floors = getFloorsByViewId($params['vw_id']);
        $fl = Arr::getValue($floors['byId'], $params['id'], false);
        if (!$fl) return $J->error('Срез данных не найден');

        $q = "UPDATE `{$this->tableviews}`
              SET def_floor = '{$params['id']}'
              WHERE id = {$params['vw_id']}";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
        }

        $J->result = true;
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VWFLOOR_DEF, array('old_value'=>$oldval['def_floor'], 'new_value'=>$params['id'], 'id'=>$params['vw_id']));

        return $J;
    }


    public function deleteFloor() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['id']       = (int)$J->readVar('id',0);
        $params['vw_id'] = (int)$J->readVar('vw_id',0);

        $all = getAllViews_();
        if (!DB::$lastReqState) return $J->error('Не удалось получить список отображений <!--'.DB::getError().'-->');
        $vw = Arr::getValue($all, $params['vw_id'], false);
        if (!is_array($vw)) return $J->error('Отображение не найдено');

        $floors = getFloorsByViewId($params['vw_id']);
        $fl = Arr::getValue($floors['byId'], $params['id'], false);
        if (!$fl) return $J->error('Срез данных не найден');

        // transaction start
        DB::$mysqli->autocommit(FALSE);

        $q = "DELETE FROM `{$this->tablefloors}` WHERE id = {$params['id']}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        if ($J->getState()) {
            $q = "DELETE FROM `{$this->tablesen}` WHERE floor_id = {$params['id']}";
            $res = DB::query($q);
            if (!$res || !DB::state()) {
                $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
            }
        }

        if ($J->getState() && $vw['def_floor'] == $params['id']) {
            $q = "UPDATE `{$this->tableviews}` SET def_floor = 0 WHERE id = {$vw['id']}";
            $res = DB::query($q);
            if (!$res || !DB::state()) {
                $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
            }
        }

        if (!$J->getState()) {
            DB::$mysqli->rollback();
            $J->result = false;
        }
        else {
            $J->result = true;
            if (class_exists('Log')) Log::Save(OPERATION::DELETE_VWFLOOR, $fl);
            DB::$mysqli->commit();
        }

        DB::$mysqli->autocommit(TRUE);
        return $J;
    }

    public function changeOrder() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['id']       = (int)$J->readVar('id',0);
        $params['vw_id']    = (int)$J->readVar('vw_id',0);
        $params['dir']      = $J->readVar('dir');

        if (!in_array($params['dir'], array('left', 'right'))) return $J->error('Неправильный запрос');

        $all = getAllViews_();
        if (!DB::$lastReqState) return $J->error('Не удалось получить список отображений <!--'.DB::getError().'-->');
        $vw = Arr::getValue($all, $params['vw_id'], false);
        if (!is_array($vw)) return $J->error('Отображение не найдено');

        $floors = getFloorsByViewId($params['vw_id']);
        $fl = Arr::getValue($floors['byId'], $params['id'], false);
        if (!$fl) return $J->error('Срез данных не найден');

        $found = false;
        foreach ($floors['byOrder'] as $key=>$f) {
            if (!($f instanceof Floor)) continue;

            if ($f->id == $params['id']) {
                $found = $f;
                $left = Arr::getValue($floors['byOrder'], $key-1, false);
                $right = Arr::getValue($floors['byOrder'], $key+1, false);
                break;
            }
        }

        if ($params['dir'] == 'left' && !$left) return $J->error('Этот элемент уже самый первый');
        if ($params['dir'] == 'right' && !$right) return $J->error('Этот элемент уже самый последний');

        $oldval = $found->view_order;

        if ($params['dir'] == 'left') {
            $found->view_order = $left->view_order;
            //$left->view_order = $oldval;
            $changedId = $left->id;
        }
        else {
            $found->view_order = $right->view_order;
            $changedId = $right->id;
        }

        // transaction start
        DB::$mysqli->autocommit(FALSE);

        $q = "UPDATE `{$this->tablefloors}`
                SET view_order = {$oldval}
                WHERE id = {$changedId}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        if ($J->getState()) {
            $q = "UPDATE `{$this->tablefloors}`
                    SET view_order = {$found->view_order}
                    WHERE id = {$found->id}";
            $res = DB::query($q);
            if (!$res || !DB::state()) {
                $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
            }
        }

        if (!$J->getState()) {
            DB::$mysqli->rollback();
            $J->result = false;
        }
        else {
            $J->result = true;
            if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VWFLOOR_ORDER, array('id'=>$found->id, 'old_val'=>$oldval, 'new_val'=>$found->view_order, 'changed_fl'=>$changedId));
            DB::$mysqli->commit();
        }

        DB::$mysqli->autocommit(TRUE);
        return $J;
    }


    public function readFLDSfields (&$J) {
        $params = array();

        $params['action']           = $J->readVar('action');
        $params['id']               = (int)$J->readVar('id',0);
        $params['floor_id']         = (int)$J->readVar('floor_id',0);
        $params['tbl']              = mysql_escape_string($J->readVar('tbl'));
        $params['sen']              = mysql_escape_string($J->readVar('sen'));
        $params['time_min']         = mysql_escape_string($J->readVar('time_min'));
        $params['time_max']         = mysql_escape_string($J->readVar('time_max'));
        $params['time_shift']        = (int)$J->readVar('time_shift',0);
        $params['whatsum']          = mysql_escape_string($J->readVar('whatsum'));
        $params['use_timelimit']    = mysql_escape_string($J->readVar('use_timelimit'));
        return $params;
    }


    public function checkFLDSFields($params) {
        $wrongFields = array();

        $name = 'tbl';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'whatsum';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        return $wrongFields;

    }


    public function updateFLDS() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = $this->readFLDSfields($J);
        $wrongFields = $this->checkFLDSFields($params);

        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }

        //$tablesen

        $q = "SELECT * FROM `{$this->tablesen}` WHERE id = {$params['id']}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при проверке данных <!--('.DB::$mysqli->error.')-->');
        }
        $oldval = $res->fetch_assoc();
        if (!is_array($oldval)) return $J->error('Источник данных не существует');

        $q = "UPDATE `{$this->tablesen}`
              SET
                    `tbl` = '{$params['tbl']}',
                    `sen` = '{$params['sen']}',
                    `time_min` = TIME('{$params['time_min']}'),
                    `time_max` = TIME('{$params['time_max']}'),
                    `time_shift` = '{$params['time_shift']}',
                    `whatsum` = '{$params['whatsum']}',
                    `use_timelimit` = '{$params['use_timelimit']}'
              WHERE id = {$params['id']}";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        $J->result = true;
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VWFLDS, array('id'=>$params['id'], 'old_val'=>$oldval, 'new_val'=>$params));
        return $J;
    }




    public function createFLDS($params=null) {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        if (!is_array($params)) {
            $params = $this->readFLDSfields($J);
            $wrongFields = $this->checkFLDSFields($params);

            if (count($wrongFields)) {
                $J->wrongFields = $wrongFields;
                return $J;
            }
        }

        $params = array_merge(array(
            'floor_id'      => 0,
            'tbl'           => 'obj_',
            'sen'           => '',
            'time_min'      => 0,
            'time_max'      => 0,
            'time_shift'    => 0,
            'whatsum'       => '',
            'use_timelimit' => 0
        ), $params);

        $q = "INSERT INTO `{$this->tablesen}`
                    (
                        `id`,
                        `floor_id`,
                        `tbl`,
                        `sen`,
                        `time_min`,
                        `time_max`,
                        `time_shift`,
                        `whatsum`,
                        `use_timelimit`
                    )
              VALUES
                    (
                        NULL,
                        '{$params['floor_id']}',
                        '{$params['tbl']}',
                        '{$params['sen']}',
                        TIME('{$params['time_min']}'),
                        TIME('{$params['time_max']}'),
                        '{$params['time_shift']}',
                        '{$params['whatsum']}',
                        '{$params['use_timelimit']}'
                    )
        ";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        $J->insertedId = DB::$mysqli->insert_id;
        $params['id'] = $J->insertedId;
        $J->ds = $params;

        if (class_exists('Log')) Log::Save(OPERATION::CREATE_VWFLDS, $params);
        return $J;
    }


    public function deleteFLDS() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['id']       = (int)$J->readVar('id',0);
        $params['action']   = $J->readVar('action');

        $q = "SELECT * FROM `{$this->tablesen}` WHERE id = {$params['id']}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при проверке данных <!--('.DB::$mysqli->error.')-->');
        }
        $oldval = $res->fetch_assoc();
        if (!is_array($oldval)) return $J->error('Источник данных не существует');

        $q = "DELETE FROM `{$this->tablesen}` WHERE id = {$params['id']}";
        DB::query($q);
        if (!DB::state()) {
            return $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        $J->result = true;
        if (class_exists('Log')) Log::Save(OPERATION::DELETE_VWFLDS, $oldval);
        return $J;


    }




    public function getTables() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $J->readVar('action');

        $J->tables = getObjTablesList(getDbTables());
        if (!DB::state()) {
            $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        return $J;
    }


    public function getTableFields() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $J->readVar('action');
        $table = mysql_escape_string($J->readVar('table'));

        $J->fields = getTableFields($table);
        if (!DB::state()) {
            $J->error('Ошибка получения списка полей таблицы <!--('.DB::$mysqli->error.')-->');
        }

        return $J;
    }








    public function getSensors() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $J->sensors = array();
        $J->readVar('action');
        $table = mysql_escape_string($J->readVar('table'));

        $tables = getObjTablesList(getDbTables());
        if (!DB::state()) return $J->error('Ошибка при проверке данных <!--('.DB::$mysqli->error.')-->');
        if (!in_array($table, $tables)) return $J->error('Таблица не существует');

        $q = "SELECT DISTINCT sen FROM $table ";
        $res = DB::query($q);
        if (!DB::state()) return $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');


        $sen = array();
        while ($row = $res->fetch_assoc()) {
            $sen[] = Arr::getValue($row, 'sen', '?');
        }

        if (!in_array('manual', $sen)) $sen[] = 'manual';

        $J->sensors = $sen;
        return $J;
    }






    public function outForm() {
        //$params = array('error'=>$this->error);
        $params = $this->fillData();
        if (!DB::$lastReqState) $this->error = 'Ошибка в базе данных <!--'.DB::getError().'-->';
        $params['error'] = $this->error;


        echo includeFile(APP_PAGE_PARTS.'forms/form_add_view.php', $params);
    }


    public function itemList() {
        //if ($this->error) $this->printOut ($this->error);

        $params = $this->fillData();
        if (!DB::$lastReqState) $this->error = 'Ошибка в базе данных <!--'.DB::getError().'-->';


        $params['error'] = $this->error;

        //echo "<pre>".print_r($params, true).'</pre>';

        //die('UnderConstruction!');

        echo includeFile(APP_PAGE_PARTS.'list_views.php', $params);
    }


    public function outPage() {
        $params = $params = $this->fillData();
        if (!DB::$lastReqState) $params['error'] = 'Ошибка в базе данных <!--'.DB::getError().'-->';

        $this->printOut(includeFile(APP_PAGE_PARTS.'page_views.php', $params));
    }




    public function printOut( $content = '' ) {

        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm(true);

        $params = array(
            'leftmenu'  => Navbar::getVerticalBar('leftmenu'),//includeFile(APP_PAGE_PARTS.'leftmenu.php'),
            'content'   => $content? $content : ''
        );
        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }



}

$page = new Page_views();

if ($page->action) {
    if ($page->action == ACTIONS::VIEW_NEW)             echo $page->itemAdd();
    if ($page->action == ACTIONS::VIEW_FROM_HIS)        echo $page->itemAddFromHistoryObject();
    if ($page->action == ACTIONS::VIEW_UPDATE)          echo $page->itemUpdate();
    if ($page->action == ACTIONS::VIEW_FLOORS_GET)      echo $page->getFloors();
    if ($page->action == ACTIONS::VIEW_FLOORS_UPDNAME)  echo $page->floorUpdateName();
    if ($page->action == ACTIONS::VIEW_CREATE_VWFLOOR)  echo $page->floorCreate();
    if ($page->action == ACTIONS::VIEW_UPDATE_DEF)      echo $page->setDefaultFloor();
    if ($page->action == ACTIONS::VIEW_DELETE_VWFLOOR)  echo $page->deleteFloor();
    if ($page->action == ACTIONS::VIEW_FLOORS_UPDORDER) echo $page->changeOrder();
    if ($page->action == ACTIONS::VIEW_UPDATE_VWFLDS)   echo $page->updateFLDS();
    if ($page->action == ACTIONS::VIEW_CREATE_VWFLDS)   echo $page->createFLDS();
    if ($page->action == ACTIONS::VIEW_DELETE_VWFLDS)   echo $page->deleteFLDS();
    if ($page->action == ACTIONS::DATA_TABLES_GET)      echo $page->getTables();
    if ($page->action == ACTIONS::DATA_TABLE_FIELDS)    echo $page->getTableFields();
    if ($page->action == ACTIONS::DATA_SENSORS_GET)     echo $page->getSensors();
}
else  {
    if (array_key_exists('getList', $_REQUEST)) {
        if (!Auth::isLogged()) inlineReLocate ('index.php');
        else $page->itemList();
    }
    else if (array_key_exists('vwForm', $_REQUEST)) {
        if (!Auth::isLogged()) inlineReLocate ('index.php');
        else $page->outForm();//die('helloworld!');
    }
    else {
        if (!Auth::isLogged()) reLocate ('index.php');

        Navbar::$expanded = 'lm-sys-web';
        Navbar::$active = 'list_vw';
        $page->outPage();
    }




}
?>